package cn.wolfcode.handler;

import cn.wolfcode.domain.OrderInfo;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import top.javatool.canal.client.annotation.CanalTable;
import top.javatool.canal.client.handler.EntryHandler;

import java.util.concurrent.TimeUnit;

/**
 * @author BAI
 */
@Slf4j
@Component
@CanalTable(value = "t_order_info")
public class OrderInfoHandler implements EntryHandler<OrderInfo> {
    private final StringRedisTemplate redisTemplate;


    private final static String ORDER_INFO_KEY = "orderInfo::orders:";

    public OrderInfoHandler(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public void insert( OrderInfo orderInfo) {
        String json = JSON.toJSONString(orderInfo);
        log.info("[订单数据变更] - 新增订单数据,{}", json);
        redisTemplate.opsForValue().set(ORDER_INFO_KEY + orderInfo.getOrderNo(), json, 60, TimeUnit.MINUTES);
    }

    @Override
    public void update(OrderInfo before, OrderInfo after) {
        String json = JSON.toJSONString(after);
        log.info("[订单数据变更] - 更新订单数据,{} -> {}", JSON.toJSONString(before), JSON.toJSONString(after));
        redisTemplate.opsForValue().set(ORDER_INFO_KEY + after.getOrderNo(), json, 60, TimeUnit.MINUTES);
    }

    @Override
    public void delete(OrderInfo orderInfo) {
        log.info("[订单数据变更] - 删除订单数据,{}", JSON.toJSONString(orderInfo));
        redisTemplate.delete(ORDER_INFO_KEY + orderInfo.getOrderNo());
    }
}